# 微信账单解析为json数据

import json
from datetime import datetime

def read_wechat_bill_csv(file_path):
    """
    Read WeChat bill data from a CSV file and return it as a string.
    
    Args:
        file_path (str): Path to the CSV file containing WeChat bill data
        
    Returns:
        str: Raw bill data as a string
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        raise FileNotFoundError(f"CSV file not found at: {file_path}")
    except Exception as e:
        raise Exception(f"Error reading CSV file: {str(e)}")

def parse_wechat_bill(raw_data):
    lines = raw_data.split("\n")
    bill_details = []
    header_info = {
        "start_time": None,
        "end_time": None,
        "export_time": None,
        "totalTransactionNum": 0,
        "inputTransaction": {
            "transaction": 0,
            "totalInput": 0.0,
        },
        "outputTransaction": {
            "transaction": 0,
            "totalOutput": 0.0,
        },
        "neutralTransaction": {
            "transaction": 0,
            "totalNeutral": 0.0,
        }
    }
    
    # 状态标志位，用于跳过非明细数据
    in_detail_section = False
    
    for line in lines:
        line = line.strip()
        
        # 提取时间信息
        # 提取时间信息
        if "起始时间" in line:
            # 处理起始时间
            start_part = line.split("起始时间")[1]
            time_str = start_part.split("[")[1].split("]")[0]
            header_info["start_time"] = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").isoformat()
            
            # 处理同一行可能存在的终止时间
            if "终止时间" in start_part:
                end_part = start_part.split("终止时间")[1]
                time_str = end_part.split("[")[1].split("]")[0]
                header_info["end_time"] = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").isoformat()
        
        if "终止时间" in line and not header_info["end_time"]:
            end_part = line.split("终止时间")[1]
            time_str = end_part.split("[")[1].split("]")[0]
            header_info["end_time"] = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").isoformat()
        
        if line.startswith("导出时间"):
            time_str = line.split("[")[1].split("]")[0]
            header_info["export_time"] = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").isoformat()
        
        # 提取总记录数
        if line.startswith("共"):
            total_num_str = line.split("共")[1].split("笔记录")[0]
            header_info["totalTransactionNum"] = int(total_num_str)
        
        # 提取收入信息
        elif line.startswith("收入："):
            income_parts = line.split("收入：")[1].split("笔")
            header_info["inputTransaction"]["transaction"] = int(income_parts[0])
            header_info["inputTransaction"]["totalInput"] = float(income_parts[1].strip().split("元")[0])
        
        # 提取支出信息
        elif line.startswith("支出："):
            expense_parts = line.split("支出：")[1].split("笔")
            header_info["outputTransaction"]["transaction"] = int(expense_parts[0])
            header_info["outputTransaction"]["totalOutput"] = float(expense_parts[1].strip().split("元")[0])
        
        # 提取中性交易信息
        elif line.startswith("中性交易："):
            neutral_parts = line.split("中性交易：")[1].split("笔")
            header_info["neutralTransaction"]["transaction"] = int(neutral_parts[0])
            header_info["neutralTransaction"]["totalNeutral"] = float(neutral_parts[1].strip().split("元")[0])
        
        # 检查是否进入账单明细列表部分
        elif "微信支付账单明细列表" in line:
            in_detail_section = True
            continue
        
        # 解析账单明细
        if in_detail_section:
            if line.startswith("交易时间"):
                headers = line.split(",")
                continue
            
            if len(line.strip()) == 0 or not line.startswith("20"):  # 跳过空行或非明细数据
                continue
                
            fields = line.split(",", len(headers) - 1)
            detail = {}
            for i, field in enumerate(fields):
                key = headers[i].strip()
                value = field.strip().replace("¥", "")  # 移除金额前的符号
                if key in ["交易时间"]:
                    detail[key] = datetime.strptime(value, "%Y-%m-%d %H:%M:%S").isoformat()
                elif key in ["金额(元)"]:
                    detail[key] = float(value)
                else:
                    detail[key] = value
            
            bill_details.append(detail)

    # 构建最终 JSON 数据
    result = {
        **header_info,
        "bill_details": bill_details
    }

    return result

# Example usage
if __name__ == "__main__":
    try:
        # Replace 'wechat_bill.csv' with your actual CSV file path
        csv_file_path = './files/extracted/微信支付账单(20250226-20250326)/微信支付账单(20250226-20250326).csv'
        raw_data = read_wechat_bill_csv(csv_file_path)
        json_data = parse_wechat_bill(raw_data)

        json_file_path = './files/extracted/微信支付账单(20250226-20250326)/微信支付账单(20250226-20250326).json'

        with open(json_file_path, 'w', encoding='utf-8') as json_file:
            json.dump(json_data, json_file, ensure_ascii=False, indent=4)
        print(f"JSON 数据已成功保存到文件: {json_file_path}")

        print(json_data)
    except Exception as e:
        print(f"Error: {str(e)}")